import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home/Home.vue'
import Cart from '@/views/Cart/Cart.vue'
import Question from "@/views/Question/Question.vue"
import User from '@/views/User/User.vue'
import LayoutContainer from '@/views/layout/LayoutContainer.vue'
import DishDetails from '@/components/Dish/DishDetails.vue'
import DishSearch from '@/components/Dish/DishSearch.vue'
import ChoiceLabel from '@/components/Label/ChoiceLabel.vue'
import store from '@/store/index.js'
import DishHist from '@/components/Dish/DishHist.vue'
import UserInfoEdit from '@/components/User/UserInfoEdit.vue'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, resolve, reject) {
  if (resolve || reject) return originalPush.call(this, location, resolve, reject)
  return originalPush.call(this, location).catch((e) => { })
}

const routes = [
  { path: '/login', name: 'login', component: () => import('@/views/Login/LoginPage.vue') }, // 登录页
  {
    path: '/',
    component: LayoutContainer,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/cart',
        component: Cart,
        meta: {
          requireAuth: true
        }
      },
      {
        path: '/question',
        component: Question,
        meta: {
          requireAuth: true
        }
      },
      {
        path: '/user',
        component: User
      }
    ]
  },
  {
    path: '/dish/:did',
    component: DishDetails,
    props: true
  },
  {
    path: '/dish-search',
    component: DishSearch,
  },
  {
    path: '/hist',
    component: DishHist,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/choiceLabel',
    component: ChoiceLabel,
    props: true,
    meta: {
      requireAuth: true
    }
  },
  {
    path: '/user-edit',
    component: UserInfoEdit,
    meta: {
      requireAuth: true
    }
  }
]

const router = new VueRouter({
  routes
})

// 登录访问拦截 => 默认是直接放行的
// 根据返回值决定，是放行还是拦截
// 返回值：
// 1. undefined / true  直接放行
// 2. false 拦回from的地址页面
// 3. 具体路径 或 路径对象  拦截到对应的地址
//    '/login'   { name: 'login' }
router.beforeEach((to, from, next) => {
  // 如果没有token, 且访问的是非登录页，拦截到登录，其他情况正常放行
  const token = store.state.tokenInfo
  if (!token && to.meta.requireAuth) {
    next({
      path: '/login',
      query: {
        redirect: to.fullPath
      }
    })
  }
  else next()
})

export default router